package com.cfets.annualAssessment.weixinService;

import com.cfets.annualAssessment.util.Constant;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.cfets.annualAssessment.weixinService.bean.KFOnlineStatus;
import com.cfets.annualAssessment.weixinService.bean.KFStatus;
import com.cfets.annualAssessment.weixinService.bean.MsgRecord;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.http.MediaDownloadRequestExecutor;
import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor;
import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor;
import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.WxMpMassVideo;
import me.chanjar.weixin.mp.bean.result.WxMpMassUploadResult;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
import org.apache.http.client.ClientProtocolException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.util.List;

/**
 * Created with MyMpServiceImpl
 * User: pual
 * Date: 2016/4/29
 * Desc:
 */
public class MyWxMpServiceImpl extends WxMpServiceImpl implements Serializable {

    @Override
    public WxMediaUploadResult mediaUpload(String mediaType, File file) throws WxErrorException {
        String url = "http://api.weixin.qq.com/cgi-bin/media/upload?type=" + mediaType;
        return execute(new MediaUploadRequestExecutor(), url, file);
    }

    @Override
    public File mediaDownload(String media_id) throws WxErrorException {
        String url = "http://api.weixin.qq.com/cgi-bin/media/get";
        return execute(new MediaDownloadRequestExecutor(wxMpConfigStorage.getTmpDirFile()), url, "media_id=" + media_id);
    }

    @Override
    public WxMpMassUploadResult massVideoUpload(WxMpMassVideo video) throws WxErrorException {
        String url = "http://api.weixin.qq.com/cgi-bin/media/uploadvideo";
        String responseContent = execute(new SimplePostRequestExecutor(), url, video.toJson());
        return WxMpMassUploadResult.fromJson(responseContent);
    }

    /**
     * 获取客服聊天记录，默认取20条
     * 详见https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044854&token=&lang=zh_CN
     * @param startTime 开始时间，unix时间戳
     * @param endTime 结束时间，unix时间戳
     * @param pageNum 第几页
     * @return
     */
    public List<MsgRecord> getCustomserviceMsgrecord(long startTime, long endTime, int pageNum) throws WxErrorException {
        String url = "https://api.weixin.qq.com/customservice/msgrecord/getrecord";
        JsonObject param = new JsonObject();
        param.addProperty("starttime", startTime/1000);
        param.addProperty("endtime", endTime/1000);
        param.addProperty("pageindex", pageNum);
        param.addProperty("pagesize", 20);
        String responseContent = post(url, param.toString());
        JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
        return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("recordlist"),
                new TypeToken<List<MsgRecord>>() {
                }.getType());
    }

    /**
     * 获取当前在线的客服的接待信息，
     * 详见https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141275&token=&lang=zh_CN
     * @return
     */
    public List<KFOnlineStatus> getKFOnlineStatus() throws WxErrorException {
        String url = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist";
        String responseContent = get(url,null);
        JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
        return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("kf_online_list"),
                new TypeToken<List<KFOnlineStatus>>() {
                }.getType());
    }

    /**
     * 获取获取客服基本信息
     * 详见https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141275&token=&lang=zh_CN
     * @return
     */
    public List<KFStatus> getKFStatus() throws WxErrorException {
        String url = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist";
        String responseContent = get(url,null);
        JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
        return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("kf_list"),
                new TypeToken<List<KFStatus>>() {
                }.getType());
    }

    /**
     * 添加客服账号,并未邀请绑定
     * 详见https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141275&token=&lang=zh_CN
     * @param kf_account 客服账号
     * @param nickname 客服昵称
     * @return
     */
    public boolean addKFaccount(String kf_account,String nickname) throws WxErrorException {
        String url = "https://api.weixin.qq.com/customservice/kfaccount/add";
        JsonObject param = new JsonObject();
        param.addProperty("kf_account", kf_account);
        param.addProperty("nickname", nickname);
        String responseContent = post(url, param.toString());
        WxError wxError = WxError.fromJson(responseContent);
        if(wxError.getErrorCode() == 0) {
            return true;
        } else {
            throw new WxErrorException(wxError);
        }
    }

    /**
     * 邀请绑定客服帐号
     * 详见https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141275&token=&lang=zh_CN
     * @param kf_account 客服账号
     * @param invite_wx 受邀请微信号
     * @return
     */
    public boolean inviteKFaccount(String kf_account,String invite_wx) throws WxErrorException {
        String url = "https://api.weixin.qq.com/customservice/kfaccount/inviteworker";
        JsonObject param = new JsonObject();
        param.addProperty("kf_account", kf_account);
        param.addProperty("invite_wx", invite_wx);
        String responseContent = post(url, param.toString());
        WxError wxError = WxError.fromJson(responseContent);
        if(wxError.getErrorCode() == 0) {
            return true;
        } else {
            throw new WxErrorException(wxError);
        }
    }


    /**
     * 修改客服帐号
     * 详见https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141275&token=&lang=zh_CN
     * @param kf_account 客服账号
     * @param nickname 客服昵称
     * @return
     */
    public boolean updateKFaccount(String kf_account,String nickname) throws WxErrorException {
        String url = "https://api.weixin.qq.com/customservice/kfaccount/update";
        JsonObject param = new JsonObject();
        param.addProperty("kf_account", kf_account);
        param.addProperty("nickname", nickname);
        String responseContent = post(url, param.toString());
        WxError wxError = WxError.fromJson(responseContent);
        if(wxError.getErrorCode() == 0) {
            return true;
        } else {
            throw new WxErrorException(wxError);
        }
    }

    /**
     * 上传客服头像
     * 详见https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141275&token=&lang=zh_CN
     * @param kf_account 客服账号
     * @param file 上传的用户头像
     * @return
     */
    public boolean uploadKFImage(String kf_account, MultipartFile file) throws WxErrorException {
        String result = execute(new com.cfets.annualAssessment.weixinService.http.MediaUploadRequestExecutor(),"https://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?kf_account="+kf_account,file);
        WxError error = WxError.fromJson(result);
        if(error.getErrorCode() == 0) {
            return true;
        } else {
            throw new WxErrorException(error);
        }
    }

    /**
     * 删除客服账号
     * 详见https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141275&token=&lang=zh_CN
     * @param kf_account 客服账号
     * @return
     */
    public boolean deleteKFaccount(String kf_account) throws WxErrorException {
        String url = "https://api.weixin.qq.com/customservice/kfaccount/del?kf_account="+kf_account;
        String responseContent = get(url,null);
        WxError wxError = WxError.fromJson(responseContent);
        if(wxError.getErrorCode() == 0) {
            return true;
        } else {
            throw new WxErrorException(wxError);
        }
    }

    /**
     * 创建一个客服回话 若当前客服不在线，报微信错误
     * 详见https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044820&token=&lang=zh_CN
     * @param kf_account 客服账号
     * @return
     */
    public boolean createKfSession(String kf_account,String openId) throws WxErrorException {
        String url = "https://api.weixin.qq.com/customservice/kfsession/create";
        JsonObject param = new JsonObject();
        param.addProperty("kf_account", kf_account);
        param.addProperty("openid", openId);
        String responseContent = post(url, param.toString());
        WxError wxError = WxError.fromJson(responseContent);
        if(wxError.getErrorCode() == 0) {
            return true;
        } else {
            throw new WxErrorException(wxError);
        }
    }

    /**
     * 获取客服会话列表
     * 详见https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044820&token=&lang=zh_CN
     * @param kf_account 客服账号
     * @return
     */
    public boolean getKFsessionList(String kf_account) throws WxErrorException {
        String url = "https://api.weixin.qq.com/customservice/kfsession/getsessionlist?kf_account="+kf_account;
        String responseContent = get(url,null);
        WxError wxError = WxError.fromJson(responseContent);
        if(wxError.getErrorCode() == 0) {
            return true;
        } else {
            throw new WxErrorException(wxError);
        }
    }

    /**
     * 给予多微信公众号需求于临时公众号认证
     * 详见原函数的oauth2getAccessToken
     * @param temp_code 会议code
     * @return
     */
    public WxMpOAuth2AccessToken getMeetingAccessToken(String temp_code) throws WxErrorException {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
        url = url + "appid=" + Constant.WX_TEMP_APPID;
        url = url + "&secret=" + Constant.WX_TEMP_SECRETID;
        url = url + "&code=" + temp_code;
        url = url + "&grant_type=authorization_code";

        try {
            SimpleGetRequestExecutor e = new SimpleGetRequestExecutor();
            String responseText = (String)e.execute(this.getHttpclient(), this.httpProxy, url, (String) null);
            return WxMpOAuth2AccessToken.fromJson(responseText);
        } catch (ClientProtocolException var5) {
            throw new RuntimeException(var5);
        } catch (IOException var6) {
            throw new RuntimeException(var6);
        }
    }

}
